﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using CPETwit.WPFClient.Business.Service;
using CPETwit.WPFClient.Business.TwitterServiceReference;
using CPETwit.WPFClient.Command;
using CPETwit.WPFClient.Common;

namespace CPETwit.WPFClient.ViewModel
{
    public class TimelineViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        #region Fields

        private ObservableCollection<Tweet> _tweets;
        private User _currentUser;
        private bool _timeline;
        private ICommand _loadCommand;
        private ICommand _refreshTimelineCommand;
        private ICommand _retweetCommand;

        #endregion

        #region Properties

        public ICommand RefreshTimelineCommand
        {
            get
            {
                return _refreshTimelineCommand ??
                    new RelayCommand(param => RefreshTimeline(),
                                     param => CanRefreshTimeline());
            }
        }
        public ICommand RetweetCommand
        {
            get
            {
                return _retweetCommand ??
                    new RelayCommand(param => Retweet(param as Tweet),
                                     param => CanRetweet());
            }
        }

        private bool CanRetweet()
        {
            return true;
        }

        private void Retweet(Tweet tweet)
        {
            ServiceManager.ReTweet(CommonData.LOGGED_USER, tweet);
            RefreshTimeline();
        }

        public ObservableCollection<Tweet> Tweets
        {
            get
            {
                return _tweets;
            }
            private set
            {
                _tweets = value;
                OnPropertyChanged("Tweets");
            }
        }

        #endregion

        /// <summary>
        /// Constructeur par défaut.
        /// </summary>
        public TimelineViewModel()
        {
            _tweets = new ObservableCollection<Tweet>();

            if (App.IsInDesignMode())
            {
                User u = new User() { name = "joe satriani", login = "test", sex = "M", avatar = null };
                Message msg = new Message() { contenu = "simple messagesimple messagesimple messagesimple message" };
                _tweets.Add(new Tweet
                                {
                                    TwitterProperty = u,
                                    MessageProperty = msg,
                                    CreatorProperty = u,
                                    UserFromProperty = u,
                                    tweetdate = DateTime.Now.AddSeconds(-10)
                                });
            }
        }

        private void RefreshTimeline()
        {
            DialogManager.UpdateTweetMenus();
            UpdateViewModel(_currentUser, _timeline);
        }
        private bool CanRefreshTimeline()
        {
            return CommonData.LOGGED_USER != null;
        }

        /// <summary>
        /// Chargement des tweets d'un utilisateur.
        /// </summary>
        /// <param name="user"></param>
        /// <param name="timeline"> </param>
        public void UpdateViewModel(User user, bool timeline)
        {
            if (user == null) throw new ArgumentNullException("user");

            _currentUser = user;
            _timeline = timeline;
            Tweets.Clear();

            IEnumerable<Tweet> tweets = timeline ?
                ServiceManager.GetTimeLineFromUser(user) :
                ServiceManager.GetTweetsFromUser(user);

            if (tweets != null)
                Tweets = new ObservableCollection<Tweet>(tweets);
        }
        public void UpdateViewModelByResearch(string research)
        {
            if (research == null) throw new ArgumentNullException("research");

            _currentUser = null;
            Tweets.Clear();

            IEnumerable<Tweet> tweets = IsTag(research) == false
                ? ServiceManager.GetTweetsBySearch(research)
                : ServiceManager.GetTweetsByTag(GetTag(research));

            if (tweets != null)
                Tweets = new ObservableCollection<Tweet>(tweets);
        }

        private bool IsTag(string research)
        {
            return research.TrimStart(' ').StartsWith("#");
        }

        private string GetTag(string research)
        {
            return research.Trim(' ');
        }
    }
}
